package com.antaohua.platfrom.framework.config;

import java.sql.SQLException;
import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.PropertySource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@EnableTransactionManagement
@ComponentScans({
	@ComponentScan(useDefaultFilters=false,basePackages="com.antaohua.platfrom.**.service",includeFilters={@Filter(type=FilterType.ANNOTATION,value=Service.class)}),
	@ComponentScan(useDefaultFilters=false,basePackages="com.antaohua.platfrom.**.dao",includeFilters={@Filter(type=FilterType.ANNOTATION,value=Repository.class)})

	})

@PropertySource(value="classpath:/config.properties",ignoreResourceNotFound=false)
public class OrmConfig 
{
	
	private final Logger logger = LoggerFactory.getLogger(OrmConfig.class);
	
	@Value("${spring.datasource.url}")  
    private String dbUrl;  
      
    @Value("${spring.datasource.username}")  
    private String username;  
      
    @Value("${spring.datasource.password}")  
    private String password;  
      
    @Value("${spring.datasource.driverClassName}")  
    private String driverClassName;  
      
    @Value("${spring.datasource.initialSize}")  
    private int initialSize;  
      
    @Value("${spring.datasource.minIdle}")  
    private int minIdle;  
      
    @Value("${spring.datasource.maxActive}")  
    private int maxActive;  
      
    @Value("${spring.datasource.maxWait}")  
    private int maxWait;  
      
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")  
    private int timeBetweenEvictionRunsMillis;  
      
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")  
    private int minEvictableIdleTimeMillis;  
      
    @Value("${spring.datasource.validationQuery}")  
    private String validationQuery;  
      
    @Value("${spring.datasource.testWhileIdle}")  
    private boolean testWhileIdle;  
      
    @Value("${spring.datasource.testOnBorrow}")  
    private boolean testOnBorrow;  
      
    @Value("${spring.datasource.testOnReturn}")  
    private boolean testOnReturn;  
      
    @Value("${spring.datasource.poolPreparedStatements}")  
    private boolean poolPreparedStatements;  
      
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")  
    private int maxPoolPreparedStatementPerConnectionSize;  
      
    @Value("${spring.datasource.filters}")  
    private String filters;  
      
    @Value("{spring.datasource.connectionProperties}")  
    private String connectionProperties;

	 
	    
	    @Bean(initMethod = "init", destroyMethod = "close")  
	    public DataSource druidDataSource() {
	    	DruidDataSource datasource = new DruidDataSource();  
	          
	        datasource.setUrl(this.dbUrl.trim());  
	        datasource.setUsername(this.username.trim());  
	        datasource.setPassword(this.password.trim());  
	        datasource.setDriverClassName(driverClassName);  
	          
	        //configuration  
	        datasource.setInitialSize(initialSize);  
	        datasource.setMinIdle(minIdle);  
	        datasource.setMaxActive(maxActive);  
	        datasource.setMaxWait(maxWait);  
	        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
	        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
	        datasource.setValidationQuery(validationQuery);  
	        datasource.setTestWhileIdle(testWhileIdle);  
	        datasource.setTestOnBorrow(testOnBorrow);  
	        datasource.setTestOnReturn(testOnReturn);  
	        datasource.setPoolPreparedStatements(poolPreparedStatements);  
	        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);  
	        try {  
	            datasource.setFilters(filters);  
	        } catch (SQLException e) {  
	            logger.error("druid configuration initialization filter", e);  
	        }  
	        datasource.setConnectionProperties(connectionProperties);  
	          
	        return datasource;  
	    }
	    
	    @Bean
		public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
			LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
			factoryBean.setDataSource(druidDataSource());
			factoryBean.setPackagesToScan(new String[] { "com.antaohua.platfrom.**.**.entity","com.antaohua.platfrom.**.entity" });
			factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
			factoryBean.setJpaProperties(jpaProperties());
			return factoryBean;
		}

	    @Bean
		public JpaVendorAdapter jpaVendorAdapter() {
			HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
			return hibernateJpaVendorAdapter;
		}
	    
	    
	    
	    /*
		 * Here you can specify any provider specific properties.
		 */
		private Properties jpaProperties() {
			Properties properties = new Properties();
			properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
			properties.put("hibernate.hbm2ddl.auto", "update");
			//properties.put("hibernate.hbm2ddl.auto", "create-drop");
			properties.put("hibernate.show_sql", true);
			properties.put("hibernate.format_sql",true);
			return properties;
		}
		
		
		

		@Bean
		@Autowired
		public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
		    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(entityManagerFactory);
		    return jpaTransactionManager;
		}
	    
	    
	    
//	    @Bean
//		  public LocalSessionFactoryBean sessionFactoryBean()
//		  {
//		    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
//		    sessionFactory.setDataSource(druidDataSource());
//		    sessionFactory.setPackagesToScan(new String[] { "com.antaohua.platfrom.**.**.entity","com.antaohua.platfrom.**.entity" });
//		    sessionFactory.setHibernateProperties(hibernateProperties());
//		    return sessionFactory;
//		  }
//	    
//
//	    
//	    final Properties hibernateProperties(){
//			  Properties pro = new Properties();
//			  pro.setProperty("hibernate.hbm2ddl.auto","update");;
//			  pro.setProperty("hibernate.show_sql", "true");
//			  pro.setProperty("hibernate.connection.useUnicode", "true");
//			  pro.setProperty("hibernate.connection.characterEncoding", "UTF-8");
//			  pro.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
//		    return pro;
//		  }
//
//
//		public PlatformTransactionManager annotationDrivenTransactionManager() {
//			 HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();  
//		        hibernateTransactionManager.setSessionFactory(sessionFactoryBean().getObject());  
//		        return hibernateTransactionManager;  
//		
//		}
}
